package logger

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"
)

// 性能聚合器，用于收集多个节点的性能数据
type PerformanceAggregator struct {
	totalNodes int
	logDir     string
	stats      map[uint64]*NodeStats
	lock       sync.RWMutex
	startTime  time.Time
}

type NodeStats struct {
	NodeID      uint64    `json:"node_id"`
	LastEpoch   uint64    `json:"last_epoch"`
	TotalTX     uint64    `json:"total_transactions"`
	AverageTPS  float64   `json:"average_tps"`
	AverageLatency float64 `json:"average_latency"`
	LastUpdate  time.Time `json:"last_update"`
}

type GlobalPerformanceReport struct {
	Timestamp     time.Time `json:"timestamp"`
	TotalNodes    int      `json:"total_nodes"`
	ActiveNodes   int      `json:"active_nodes"`
	GlobalTPS     float64  `json:"global_tps"`
	AverageLatency float64 `json:"average_latency"`
	TotalTX       uint64   `json:"total_transactions"`
	NetworkStats  map[string]interface{} `json:"network_stats"`
}

func NewPerformanceAggregator(totalNodes int, logDir string) *PerformanceAggregator {
	return &PerformanceAggregator{
		totalNodes: totalNodes,
		logDir:     logDir,
		stats:      make(map[uint64]*NodeStats),
		startTime:  time.Now(),
	}
}

func (pa *PerformanceAggregator) UpdateNodeStats(nodeID uint64, epoch uint64, totalTX uint64, tps float64, latency float64) {
	pa.lock.Lock()
	defer pa.lock.Unlock()
	
	pa.stats[nodeID] = &NodeStats{
		NodeID:        nodeID,
		LastEpoch:     epoch,
		TotalTX:       totalTX,
		AverageTPS:    tps,
		AverageLatency: latency,
		LastUpdate:    time.Now(),
	}
}

func (pa *PerformanceAggregator) GenerateReport() GlobalPerformanceReport {
	pa.lock.RLock()
	defer pa.lock.RUnlock()
	
	var globalTPS, totalLatency float64
	var totalTX uint64
	activeNodes := 0
	
	for _, stats := range pa.stats {
		// 检查节点是否活跃（最近30秒内有更新）
		if time.Since(stats.LastUpdate) < 30*time.Second {
			activeNodes++
			globalTPS += stats.AverageTPS
			totalLatency += stats.AverageLatency
			totalTX += stats.TotalTX
		}
	}
	
	avgLatency := float64(0)
	if activeNodes > 0 {
		avgLatency = totalLatency / float64(activeNodes)
	}
	
	return GlobalPerformanceReport{
		Timestamp:     time.Now(),
		TotalNodes:    pa.totalNodes,
		ActiveNodes:   activeNodes,
		GlobalTPS:     globalTPS,
		AverageLatency: avgLatency,
		TotalTX:       totalTX,
		NetworkStats:  pa.getNetworkStats(),
	}
}

func (pa *PerformanceAggregator) getNetworkStats() map[string]interface{} {
	// 模拟网络统计信息
	return map[string]interface{}{
		"network_type": "WAN",
		"latency_range": "20-100ms",
		"bandwidth": "200-1000 Mbps",
		"packet_loss": "0.1-1%",
	}
}

func (pa *PerformanceAggregator) SaveReport(report GlobalPerformanceReport) error {
	// 确保日志目录存在
	if err := os.MkdirAll(pa.logDir, 0755); err != nil {
		return fmt.Errorf("failed to create log directory: %v", err)
	}
	
	// 生成报告文件名
	timestamp := time.Now().Format("2006-01-02_15-04-05")
	reportFile := filepath.Join(pa.logDir, fmt.Sprintf("global_report_%s.json", timestamp))
	
	// 写入报告
	jsonData, err := json.MarshalIndent(report, "", "  ")
	if err != nil {
		return fmt.Errorf("failed to marshal report: %v", err)
	}
	
	return os.WriteFile(reportFile, jsonData, 0644)
}

func (pa *PerformanceAggregator) PrintReport() {
	report := pa.GenerateReport()
	
	fmt.Printf("\n=== Global Performance Report ===\n")
	fmt.Printf("Timestamp: %s\n", report.Timestamp.Format("2006-01-02 15:04:05"))
	fmt.Printf("Total Nodes: %d\n", report.TotalNodes)
	fmt.Printf("Active Nodes: %d\n", report.ActiveNodes)
	fmt.Printf("Global TPS: %.2f TX/s\n", report.GlobalTPS)
	fmt.Printf("Average Latency: %.2f ms\n", report.AverageLatency)
	fmt.Printf("Total Transactions: %d\n", report.TotalTX)
	fmt.Printf("Network: %s\n", report.NetworkStats["network_type"])
	fmt.Printf("================================\n")
}
